package com.spider.utils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author 罗振军
 * @version V1.0
 * @Package com.spider.utils
 * @date 2024/7/19 16:15
 */
public class WebUtils {

    /**
     * 封装响应
     * 将给定的字符串渲染到HTTP响应中
     * easyExcel文件导出失败时候做的操作
     * @param response
     * @param string
     */
    public static void renderString(HttpServletResponse response, String string) {
        try
        {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * easyExcel文件导出
     * @param filename
     * @param response
     * @throws UnsupportedEncodingException
     */
    public static void setDownLoadHeader(String filename, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fname= URLEncoder.encode(filename,"UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition","attachment; filename="+fname);
    }

//    /**
//     * 设置下载文件的请求头
//     *
//     * @param filename 文件名
//     * @param response 响应
//     */
//    public static void setDownLoadHeader
//    (String filename, ServletContext context, HttpServletResponse response)
//            throws UnsupportedEncodingException {
//        String mimeType = context.getMimeType(filename);//获取文件的MIME类型
//        response.setHeader("content-type", mimeType);//将MIME类型设置为"content-type"响应头的值
//        String fname = URLEncoder.encode(filename, "UTF-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fname);
//
//        //下面两行是另一种设置响应头的方式，现在已经不经常用了
////        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
////        response.setCharacterEncoding("utf-8");
//    }


}
